package de.carcophan.jimdb.service.servlets;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;

import org.jboss.logging.Logger;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import de.carcophan.jimdb.gwt.client.service.MovieService;
import de.carcophan.jimdb.gwt.server.Session;
import de.carcophan.jimdb.gwt.shared.entites.Movie;
import de.carcophan.jimdb.gwt.shared.entites.Tag;
import de.carcophan.jimdb.gwt.shared.entites.UserMovies;
import de.carcophan.jimdb.service.QueryController;
import de.carcophan.jimdb.service.sessionbeans.ServiceSessionBean;

@WebServlet(name = "movieSerlvet", urlPatterns = { "/jimdb/movie" })
public class MovieServiceImpl extends RemoteServiceServlet implements
		MovieService {

	private static Logger logger = Logger.getLogger(MovieServiceImpl.class);

	private static final long serialVersionUID = 1L;
	@EJB
	private ServiceSessionBean serviceSessionBean;
	@Inject
	private QueryController queryController;
	@Inject
	private Session session;

	@Override
	public List<UserMovies> findMovieBySearchValue(String value) {
		List<Movie> result = null;
		List<UserMovies> userMovies = new ArrayList<UserMovies>();
		try {
			result = serviceSessionBean.fromImdbApi(value);
			for (Movie movie : result) {
				UserMovies userMovie = queryController.findSingleUserMovie(
						movie.getImdbId(), session.getUser().getId());
				if (userMovie == null) {
					userMovie = new UserMovies();
					userMovie.setMovie(movie);
				}
				userMovie.setUser(null);
				userMovies.add(userMovie);

			}
		} catch (Exception e) {
			throw new JimdbRemoteException(e);
		}
		return userMovies;
	}

	@Override
	public List<Tag> addTag(String tag, String hexColor) {
		System.out.println(hexColor);
		tag = tag.trim().toUpperCase();
		serviceSessionBean.addTag(tag, hexColor);
		return findAllTags();
	}

	@Override
	public List<Tag> findAllTags() {
		List<Tag> tags = queryController.findAllTags();
		return tags;
	}

	@Override
	public void saveTag(String imdbId, String selectedTag) {
		serviceSessionBean.saveTag(imdbId, selectedTag);

	}

	@Override
	public Tag findTagForMovie(String imdbId) {
		UserMovies userMovie = queryController.findSingleUserMovie(imdbId,
				session.getUser().getId());
		Tag result = null;
		if (userMovie != null) {
			result = userMovie.getTag();
		}
		return result;
	}

	@Override
	public List<UserMovies> loadMovies() {
		List<UserMovies> movies = queryController.loadMovies();
		for (UserMovies userMovies : movies) {
			userMovies.setUser(null);
		}
		return movies;
	}
}
